<?php
namespace app\controller;

use app\BaseController;
// use app\controller\ForwardController;
use app\middleware\Auth;
use app\model\Elevator;
use app\model\ElevatorNdata;
use app\model\Project;
use app\model\TowerAlarmNdata;
use app\model\TowerAlarmRdata;
use app\model\TowerAnticollision;
use app\model\TowerCrane;
use app\model\TowerCraneNdata;
use app\model\TowerCraneRdata;
use app\model\TowerCraneWorkData;
use app\model\User;
use GuzzleHttp\Client;
use think\facade\Cache;
use think\facade\Log;
use think\Request;

//use think\facade\Db;
/* 塔机设备控制器 */

class TowerController extends BaseController
{
    /* 控制器私有变量 */
    private $alarm_array = ['正常', '高度上限预警', '高度上限报警', '幅度近限预警', '幅度近限报警', '幅度远限预警', '幅度远限报警', '重量预警', '重量报警', '力矩预警', '力矩报警', '风速预警', '风速报警', '防碰撞左转预警', '防碰撞左转报警', '防碰撞右转预警', '防碰撞右转报警', '倾角预警', '倾角报警']; //报警数据字典
    protected $middleware = [Auth::class]; //控制器中间件

    /* 设备接口 */
    public function towerInfo(Request $request)
    {
        $where = [];
        if ($request->has('mac')) {
            $mac = $request->param('mac');
            $where[] = ['mac', 'like', '%' . $mac . '%'];
        }
        if ($request->has('eid')) {
            $eid = $request->param('eid');
            $where[] = ['eid', '=', $eid];
        }
        $equipment = TowerCrane::where($where)->find();
        if ($equipment) {
            return success($equipment);
        } else {
            return fail(null, '设备ID不存在', 0);
        }
    }
    //设备更新信息
    public function updateTowerEquipment()
    {
        $request = $this->request->param();
        // Log::write($this->request->param(), 'Request_updateTowerEquipment');
        $equipment = TowerCrane::where('eid', $request['eid'])->find();
        if (!$equipment) {
            return fail(null, '设备ID不存在', 0);
        }

        foreach ($request as $key => $value) {
            if (is_double($value)) {
                $value = round($value, 2);
            }
            $equipment->$key = $value;
        }
        $re = $equipment->save();
        if ($re) {

            if ($this->request->has('online')) {
                /* 判断开关机转发数据 */
                $forward_id = TowerCraneNdata::where('eid', $request['eid'])->find()->forward_id;
                if ($forward_id == 109) {
                    if ($request['online'] == 1) {
                        $event_type = 1;
                    } else {
                        $event_type = 2;
                    }
                    $url = 'https://api.xingdagz.com/v1/Tanyue/switchData';
                    $param = [
                        "eid" => $request['eid'],
                        "event_type" => $event_type,
                        "work_time" => 0,
                    ];
                    $client = new Client;
                    $response = $client->request('POST', $url, [
                        'json' => $param,
                    ])->getBody();
                    $stringBody = (string) $response;
                    // Log::write($send_json, 'ForwardController109');
                    // Log::write($stringBody, 'ForwardController109');
                }

                $online['online'] = $equipment->online;
                return success($online);
            }
            return success($equipment);
        } else {
            return fail(null, '无内容', 0);
        }
    }
    //塔机防碰撞数据
    public function addAnticollision(Request $request)
    {
        // Log::write($this->request->param(), 'addAnticollision');
        $datas = $request->param('anticollision');
        $filter = [
            'main_id' => $datas[0]['id'],
        ];
        $anticollision = TowerAnticollision::where($filter)->find();
        $towerEquipment = TowerCrane::where('eid', $datas[0]['id'])->find();
        if (!$anticollision) {
            $anticollision = new TowerAnticollision;
        }
        $slave_ids = '';
        $slave_names = '';
        $slave_arm_lengths = '';
        $slave_distances = '';
        $slave_angles = '';
        $slave_height = '';
        $anticollision->early_warning = $request->param('early_warning');
        $anticollision->alarm_value = $request->param('alarm_value');
        foreach ($datas as $keys => $data) {
            if ($keys == 0) {
                $anticollision->main_id = $data['id'];
                $anticollision->main_name = $data['name'];
                $anticollision->main_arm_length = $data['arm_length'];
                $anticollision->max_height = $data['max_height'];
                $towerEquipment->max_height = $data['max_height'];

            } else {
                if ($keys == 1) {
                    $slave_ids = $data['id'];
                    $slave_names = $data['name'];
                    $slave_arm_lengths = $data['arm_length'];
                    $slave_distances = $data['distance'];
                    $slave_angles = $data['angle'];
                    $slave_height = $data['height'];
                } else {
                    $slave_ids = $slave_ids . ',' . $data['id'];
                    $slave_names = $slave_names . ',' . $data['name'];
                    $slave_arm_lengths = $slave_arm_lengths . ',' . $data['arm_length'];
                    $slave_distances = $slave_distances . ',' . $data['distance'];
                    $slave_angles = $slave_angles . ',' . $data['angle'];
                    $slave_height = $slave_height . ',' . $data['height'];
                }
            }
        }
        $anticollision->slave_ids = $slave_ids;
        $anticollision->slave_names = $slave_names;
        $anticollision->slave_arm_lengths = $slave_arm_lengths;
        $anticollision->slave_distances = $slave_distances;
        $anticollision->slave_angles = $slave_angles;
        $anticollision->slave_height = $slave_height;
        $rq = $towerEquipment->save();
        $rq = $anticollision->save();
        return success($rq);
    }
    //空间限位数据记录
    public function spaceLimit(Request $request)
    {
        $space_limit = $request->param('spaceLimit');
        $mainID = $request->param('id');
        $filter = [
            'main_id' => $request->param('id'),
        ];
        $anticollision = TowerAnticollision::where($filter)->find();
        $towerEquipment = TowerCrane::where('eid', $request->param('id'))->find();
        if (!$anticollision) {
            $anticollision = new TowerAnticollision;
        }
        $anticollision->uid = $towerEquipment->uid;
        $height_start = '';
        $height_end = '';
        $amplitude_start = '';
        $amplitude_end = '';
        $angle_start = '';
        $angle_end = '';
        foreach ($space_limit as $limitKeys => $limit) {
            if ($limitKeys == 0) {
                $height_start = $limit['height_start'];
                $height_end = $limit['height_end'];
                $amplitude_start = $limit['amplitude_start'];
                $amplitude_end = $limit['amplitude_end'];
                $angle_start = $limit['angle_start'];
                $angle_end = $limit['angle_end'];
            } else {
                $height_start = $height_start . ',' . $limit['height_start'];
                $height_end = $height_end . ',' . $limit['height_end'];
                $amplitude_start = $amplitude_start . ',' . $limit['amplitude_start'];
                $amplitude_end = $amplitude_end . ',' . $limit['amplitude_end'];
                $angle_start = $angle_start . ',' . $limit['angle_start'];
                $angle_end = $angle_end . ',' . $limit['angle_end'];
            }
        }

        $anticollision->main_id = $mainID;
        $anticollision->height_start = $height_start;
        $anticollision->height_end = $height_end;
        $anticollision->amplitude_start = $amplitude_start;
        $anticollision->amplitude_end = $amplitude_end;
        $anticollision->angle_start = $angle_start;
        $anticollision->angle_end = $angle_end;
        $rq = $anticollision->save();
        return success($rq);
    }
    //添加循环吊次数据
    public function towerCraneWorkdata(Request $request)
    {
        $workdata = new TowerCraneWorkData;
        $data = $request->post();
        foreach ($data as $key => $value) {
            if (is_double($value)) {
                $value = round($value, 2);
                $data[$key] = $value;
            }
            $workdata->$key = $value;
        }
        //吊次时间判断 2024-03-06
        $start_time = $data['start_time'];
        $start_time = strtotime($start_time);
        $end_time = $data['end_time'];
        $end_time = strtotime($end_time);
        $index_time = $end_time - $start_time;
        if ($index_time < 10) {
            return 0;
        }
        $forwardarray = [12110143, 12110134, 12110137, 13060825, 13060830, 13060811, 13060829, 13020350, 13060824, 12110109, 13020349, 13020338, 13040597, 13040574, 13060826, 13060817, 13050633, 13020352, 13050636, 13071032, 13071033, 13071035, 13071047, 13071038, 13071053, 13071052, 13071048, 13071045, 13071040, 13071039, 13071034, 13071043, 13071002, 13070993, 13071041, 13071044, 13071037, 13081168, 13081165, 13081184, 13070994, 13071006, 13070997, 13071049, 13071051, 13071036, 13081187, 13071031, 13071008, 13071042, 13081177, 13081179, 13081178, 13081174, 13081197, 13081196, 13081193, 13081191, 13081185, 13071050, 13081182, 13091226, 13050620, 13050749, 13081183, 13081186, 13111486, 13040493, 13071008, 13071031, 13121501, 13121502, 13121504, 13121508, 13121507, 13121503, 13121506, 13121505, 13121509, 13121514, 14011603, 14011602, 14011601, 13111371, 13121578, 13121597, 13121571, 13121580, 13121586, 13121575, 13121594, 13121591, 13121581, 13121589, 13121590, 13121596, 13121582, 14011689, 14011687, 14011683, 14011684, 14031762, 14031754, 14031783, 14031782, 14031781, 14031786, 14031784, 13101348, 13101350, 14031785, 13081166, 13081167,14031758,14031763,14031776,14031765,14031774,14031760,14031775,14031755,14031761];
        if (in_array($data['eid'], $forwardarray)) {
            $cases = [
                12110143 => 1,
                12110134 => 2,
                12110137 => 2,
                13060825 => 3,
                13060830 => 3,
                13060811 => 3,
                13060829 => 3,
                13020350 => 3,
                13060824 => 3,
                12110109 => 4,
                13020349 => 4,
                13020338 => 4,
                13040597 => 4,
                13040574 => 4,
                13060826 => 4,
                13060817 => 4,
                13050633 => 4,
                13020352 => 4,
                13050636 => 4,
                13071002 => 4,
                13070993 => 4,
                13070994 => 4,
                13071006 => 4,
                13070997 => 4,
                13091226 => 4,
                13050620 => 4,
                13071032 => 5,
                13071033 => 5,
                13071035 => 5,
                13071047 => 5,
                13071038 => 5,
                13071053 => 5,
                13071052 => 5,
                13071048 => 5,
                13071045 => 5,
                13071040 => 5,
                13071039 => 5,
                13071034 => 5,
                13071043 => 5,
                13071041 => 5,
                13071044 => 5,
                13081168 => 5,
                13081165 => 5,
                13081184 => 5,
                13071049 => 5,
                13071051 => 5,
                13071036 => 5,
                13081187 => 5,
                13071037 => 5,
                13071042 => 5,
                13081174 => 5,
                13081177 => 5,
                13081178 => 5,
                13081179 => 5,
                13081197 => 5,
                13071050 => 5,
                13081185 => 5,
                13081182 => 5,
                13081183 => 5,
                13081186 => 5,
                13081196 => 5,
                13081193 => 5,
                13081191 => 5,
                13111486 => 5,
                13121501 => 5,
                13121502 => 5,
                13121503 => 5,
                13121506 => 5,
                13121508 => 5,
                13121504 => 5,
                13121505 => 5,
                13121509 => 5,
                13121507 => 5,
                14011602 => 5,
                14011601 => 5,
                14011603 => 5,
                13121514 => 5,
                14011689 => 5,
                14011687 => 5,
                14011683 => 5,
                14011684 => 5,
                14031762 => 5,
                14031754 => 5,
                14031783 => 5,
                14031781 => 5,
                14031782 => 5,
                14031784 => 5,
                14031785 => 5,
                13081166 => 5,
                13081167 => 5,
                14031758 => 5, 
                14031763 => 5,
                14031776 => 5,
                14031765 => 5,
                14031774 => 5,
                14031760 => 5,
                14031775 => 5,
                14031755 => 5,
                14031761 => 5,
                13071031 => 6,
                13071008 => 6,
                13050749 => 7,
                13040493 => 8,
                13071008 => 9,
                13071031 => 9,
                13111371 => 10,
                13121578 => 11,
                13121597 => 11,
                13121571 => 11,
                13121580 => 11,
                13121586 => 11,
                13121575 => 11,
                13121594 => 11,
                13121591 => 11,
                13121581 => 11,
                13121589 => 11,
                13121590 => 11,
                13121596 => 11,
                13121582 => 11,
                14031786 => 12,
                13101348 => 13,
                13101350 => 13,
            ];
            $case = $cases[$data['eid']];
            $this->forwardWorkdata($data, $case);
        }

        $rq = $workdata->save();
        // $equipment = TowerCrane::where('eid', $request['eid'])->find();
        return success($rq);
    }
    /* 平台接口 */
    public function towerList(Request $request)
    {
        $user = $request->user;

        $where = [];
        if ($request->has('ename', 'get', true)) {
            $ename = $request->param('ename');
            $where[] = ['ename', 'like', '%' . $ename . '%'];
        }
        if ($request->has('eid', 'get', true)) {
            $eid = $request->param('eid');
            // $where[] = ['eid', '=', $eid];
            $where[] = ['eid', 'like', '%' . $eid . '%'];
        }
        if ($request->has('pid', 'get', true)) {
            $pid = $request->param('pid');
            $where[] = ['pid', '=', $pid];
        }
        if ($request->has('mac', 'get', true)) {
            $mac = $request->param('mac');
            $where[] = ['mac', 'like', '%' . $mac . '%'];
        }

        if ($user->identity == 'user') {
            $uid = $user->id;
            $where[] = ['uid', '=', $uid];
        } elseif ($user->identity == 'sale') {
            $belong_id = $user->id;
            $users = User::where('belong_id', $belong_id)->column('id');
            $where[] = ['uid', 'in', $users];
        }
        $equipment = TowerCrane::where($where)->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        /* 禁用轮询--添加额外信息 */
        $userList = User::select()->toArray();
        $projectList = Project::select()->toArray();
        $name = array_column($userList, 'name', 'id');
        $username = array_column($userList, 'username', 'id');
        $pname = array_column($projectList, 'pname', 'id');
        //增加额外数据
        foreach ($equipment as $key => $value) {
            if ($value->uid == 0 || $value->pid == 0) {
                $value->uname = '';
                $value->username = '';
                $value->pname = '';
            } else {
                $value->uname = $name[$value->uid];
                $value->username = $username[$value->uid];
                $value->pname = $pname[$value->pid];
            }

        }
        if ($request->has('pname', 'get', true)) {
            $pname = $request->param('pname');
            $equipment = $equipment->where('pname', 'like', $pname);
        }
        if ($request->has('username', 'get', true)) {
            $username = $request->param('username');
            $equipment = $equipment->where('username', 'like', $username);
        }

        return pageReturn($equipment);
    }
    /* 塔机循环数据 */
    public function towerCraneWorkDataList(Request $request)
    {
        $where = [];
        if ($request->has('eid', 'get', true)) {
            $eid = $request->param('eid');
            $where[] = ['eid', '=', $eid];
        }
        if ($request->has('create_time', 'get', true)) {
            $create_time = $request->param('create_time');
            $where[] = ['create_time', '>=', $create_time[0]];
            $where[] = ['create_time', '<=', $create_time[1]];
        }
        $list = TowerCraneWorkData::where($where)->order('id desc')->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($list);

    }
    /* 历史数据&实时数据 */
    public function towerCraneRdata(Request $request)
    {
        $where = [];
        if ($request->has('eid', 'get', true)) {
            $eid = $request->param('eid');
            $where[] = ['eid', '=', $eid];
        }
        if ($request->has('create_time', 'get', true)) {
            $create_time = $request->param('create_time');
            $where[] = ['create_time', '>=', $create_time[0]];
            $where[] = ['create_time', '<=', $create_time[1]];
        }
        $list = TowerCraneRdata::where($where)->order('id desc')->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($list);

    }
    public function towerCraneNdata(Request $request)
    {
        $where = [];
        if ($request->has('eid', 'get', true)) {
            $eid = $request->param('eid');
            $where[] = ['eid', '=', $eid];
        }
        $data_one = TowerCraneNdata::where($where)->find();
        return success($data_one);
    }
    /* 报警数据相关 */
    public function towerAlarmRdata(Request $request)
    {
        $user = $request->user;
        $where = [];
        if ($request->has('eid', 'get', true)) {
            $eid = $request->param('eid');
            $where[] = ['eid', '=', $eid];
        }
        if ($request->has('mac', 'get', true)) {
            $mac = $request->param('mac');
            $where[] = ['mac', 'like', '%' . $mac . '%'];
        }
        if ($request->has('create_time', 'get', true)) {
            $create_time = $request->param('create_time');
            $where[] = ['create_time', '>=', $create_time[0]];
            $where[] = ['create_time', '<=', $create_time[1]];
        }
        if ($user->identity == 'user') {
            $uid = $user->id;
            $eids = TowerCrane::where('uid', '=', $uid)->column('eid');
            $where[] = ['eid', 'in', $eids];
        } elseif ($user->identity == 'sale') {
            $belong_id = $user->id;
            $users = User::where('belong_id', $belong_id)->column('id');
            $eids = TowerCrane::where('uid', 'in', $users)->column('eid');
            $where[] = ['eid', 'in', $eids];
            $list = TowerAlarmNdata::where($where)->order('id desc')->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
            /* 禁用轮询--添加额外信息 */
            $userList = User::select()->toArray();
            $projectList = Project::select()->toArray();
            $towerList = TowerCrane::select()->toArray();

            $username = array_column($userList, 'username', 'id');
            $pname = array_column($projectList, 'pname', 'id');
            $ename = array_column($towerList, 'ename', 'eid');
            $pids = array_column($towerList, 'pid', 'eid');
            $uids = array_column($towerList, 'uid', 'eid');
            //增加额外数据
            foreach ($list as $key => $value) {
                if ($value->eid == 0) {
                    $value->ename = '';
                    $value->pname = '';
                    $value->username = '';
                } else {
                    $value->ename = $ename[$value->eid];
                    $pid = $pids[$value->eid];
                    $uid = $uids[$value->eid];
                    $value->pname = $pname[$pid];
                    $value->username = $username[$uid];
                }

            }
            if ($request->has('pname', 'get', true)) {
                $pname = $request->param('pname');
                $list = $list->where('pname', 'like', $pname);
            }
            if ($request->has('username', 'get', true)) {
                $username = $request->param('username');
                $list = $list->where('username', 'like', $username);
            }
            return pageReturn($list);
        }
        $list = TowerAlarmRdata::where($where)->order('id desc')->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($list);
        // $list->each(function ($item, $key) {
        //     $item->type_name = $this->alarm_array[$item->type];
        //     }
        // );
    }
    public function towerAlarmNdata(Request $request)
    {
        $where = [];
        if ($request->has('eid', 'get', true)) {
            $eid = $request->param('eid');
            $where[] = ['eid', '=', $eid];
        }
        $data_one = TowerAlarmNdata::where($where)->find();
        return success($data_one);
    }
    //嵌入页面防碰撞接口
    public function anticollisionEmbed(Request $request)
    {
        if ($request->has('pid')) {
            $pid = $request->param('pid');
            $list = TowerCrane::where('pid', $pid)->field('eid as id,ename as name')->select();
            if (count($list) > 0) {
                $eids = [];
                $status_data = [];
                $Anticollision_data = [];
                $list_data = [];
                foreach ($list as &$option0) {
                    $eids[] = $option0->id;
                    $option0->online_status = 0;
                    $option0->height = '--';
                    $option0->wind_speed = '--';
                    $option0->status = [
                        'weight' => '0',
                        'height' => '0',
                        'amplitude' => '0',
                        'round' => '0',
                        'moment_percent' => '0',
                        'wind_speed' => '0',
                        'angle_x' => '0',
                    ];
                    $option0->Anticollision = [
                        'main_name' => $option0->name,
                        'main_arm_length' => $option0->arm_length,
                        'round' => 0,
                        'slave_names' => [],
                        'slave_arm_lengths' => [],
                        'slave_distances' => [],
                        'slave_angles' => [],
                        'angles' => [],
                    ];
                    $list_data[$option0->id] = $option0;
                }
                unset($option0);
                $status = TowerCraneNdata::whereIn('eid', $eids)->field('eid,weight,height,amplitude,round,moment_percent,wind_speed,angle_x,update_time')->select();
                $TowerAnticollision = TowerAnticollision::whereIn('main_id', $eids)->field('main_id,main_name,main_arm_length,slave_ids,slave_names,slave_arm_lengths,slave_distances,slave_angles')->select();
                foreach ($status as $statu) {
                    $status_data[$statu->eid] = $statu;
                }
                foreach ($TowerAnticollision as $Anticollision) {
                    $Anticollision_data[$Anticollision->main_id] = $Anticollision;
                }
                foreach ($list as &$option) {
                    if (array_key_exists($option->id, $status_data)) {
                        $option->height = $status_data[$option->id]->height;
                        $option->wind_speed = $status_data[$option->id]->wind_speed;
                        $option->status = [
                            'weight' => $status_data[$option->id]->weight,
                            'height' => $status_data[$option->id]->height,
                            'amplitude' => $status_data[$option->id]->amplitude,
                            'round' => $status_data[$option->id]->round,
                            'moment_percent' => $status_data[$option->id]->moment_percent,
                            'wind_speed' => $status_data[$option->id]->wind_speed,
                            'angle_x' => $status_data[$option->id]->angle_x,
                        ];
                    }
                    if (array_key_exists($option->id, $Anticollision_data)) {
                        $Anticollision = [
                            'main_name' => $option->name,
                            'main_arm_length' => $Anticollision_data[$option->id]->main_arm_length,
                            'round' => array_key_exists($option->id, $status_data) ? $status_data[$option->id]->round : 0,
                        ];
                        $slave_ids = explode(',', $Anticollision_data[$option->id]->slave_ids);
                        $slave_names = [];
                        foreach ($slave_ids as $slave_id) {
                            $slave_names[] = array_key_exists($slave_id, $list_data) ? $list_data[$slave_id]->name : '';
                        }
                        $Anticollision['slave_names'] = $slave_names;
                        $Anticollision['slave_arm_lengths'] = explode(',', $Anticollision_data[$option->id]->slave_arm_lengths);
                        $Anticollision['slave_distances'] = explode(',', $Anticollision_data[$option->id]->slave_distances);
                        $Anticollision['slave_angles'] = explode(',', $Anticollision_data[$option->id]->slave_angles);
                        $round = [];
                        foreach ($slave_ids as $eid) {
                            if (array_key_exists($eid, $status_data)) {
                                $round[] = $status_data[$eid]->round;
                            } else {
                                $round[] = 0;
                            }
                        }
                        $Anticollision['angles'] = $round;
                        $option->Anticollision = $Anticollision;
                    }
                };
                unset($option);
                return success($list);
            } else {
                return fail(null, "暂无数据");
            }
        } else {
            return fail(null, "参数有误");
        }

    }
    public function onlineFind(Request $request)
    {
        $create_time = $request->param('create_time');
        $eid = $request->param('eid');
        $list1 = [];
        $list = [];
        $sum = 0;
        $sum_put = 0;
        $i = 0;
        for ($h = 0; $h < 24; $h++) {
            $hour = str_pad($h, 2, "0", STR_PAD_LEFT);
            for ($m = 0; $m < 60; $m++, $i++) {
                $minute = str_pad($m, 2, "0", STR_PAD_LEFT);
                $list1[$i] = $hour . ':' . $minute;
            }
        }

        $list2 = TowerCraneRdata::where('eid', $eid)->whereDay('create_time', $create_time)->column('create_time');
        foreach ($list2 as $key => $value) {
            $list2[$key] = date('H:i', strtotime($value));
        }
        foreach ($list1 as $key => $value) {
            $in = (int) in_array($value, $list2);
            $list[$key]['time'] = $value;
            $list[$key]['status'] = $in;
            if (!$in) {
                $sum += 1;
                if ($sum == 1) {
                    $error[]['error'] = $list[$key]['time'];
                }
            }
            if ($sum > 2 && $in == 1) {
                $sum_put += 1;
                $sum = 0;
                $error[]['success'] = $list[$key]['time'];
            }
        }
        $return['sum_put'] = $sum_put;
        $return['list'] = $list;
        $return['error'] = $error;
        // $return['success'] =$success;
        return success($return['list']);
    }
    //在线状态判断--脚本下线
    public function equipmentOffline(Request $request)
    {
        $time = date('Y-m-d H:i:s', time() - 300);
        /* 塔机 */
        $equipmentOnline = TowerCraneNdata::where('update_time', '<', $time)->column('eid');
        $reOnline = TowerCrane::where('eid', 'in', $equipmentOnline)
            ->data(['online' => 0])
            ->update();
        $equipmentOffline = TowerCraneNdata::where('update_time', '>', $time)->column('eid');
        $reOffline = TowerCrane::where('eid', 'in', $equipmentOffline)
            ->data(['online' => 1])
            ->update();
        /* 升降机 */
        $equipmentOnline = ElevatorNdata::where('update_time', '<', $time)->column('eid');
        $reOnline = Elevator::where('eid', 'in', $equipmentOnline)
            ->data(['online' => 0])
            ->update();
        $equipmentOffline = ElevatorNdata::where('update_time', '>', $time)->column('eid');
        $reOffline = Elevator::where('eid', 'in', $equipmentOffline)
            ->data(['online' => 1])
            ->update();
        return success($reOffline);

    }
    //吊次转发
    public function forwardWorkdata($data, $variable)
    {
        switch ($variable) {
            case 1:
                //于-日照客户-tianxi-塔机吊次
                $url = 'http://rizhaotianxi.qd27.com/api/tower_loop';
                $code = 'M007';
                $time = time();
                $token = 'M00720221227T';
                $sign = md5($token . $time);
                $send['code'] = $code;
                $send['sign'] = $sign;
                $send['time'] = $time;
                $send['data'] = [
                    "equipment_no" => $data['eid'],
                    "start_height" => $data['start_height'],
                    "start_range" => $data['start_range'],
                    "start_rotation_angle" => $data['start_rotation_angle'],
                    "end_height" => $data['end_height'],
                    "end_range" => $data['end_range'],
                    "end_rotation_angle" => $data['end_rotation_angle'],
                    "weight" => $data['weight'],
                    "eforce" => $data['moment_percent'],
                    "start_time" => strtotime($data['start_time']),
                    "end_time" => strtotime($data['end_time']),
                ];
                $client = new Client;
                $response = $client->request('POST', $url, [
                    'json' => $send,
                ])->getBody();
                $stringBody = (string) $response;
                // Log::write($stringBody, 'towerCraneWorkdata');
                break;
            case 2:
                //宁津塔机-于
                $url = 'http://nj.qdgcit.com:8889/qdoner/datarecept/dataUpload/towerEffect/saveData';
                $deviceSn = [
                    '12110134' => 616,
                    '12110137' => 617,
                ];
                $send[] = [
                    "projectId" => 188,
                    "deviceSn" => $deviceSn[$data['eid']],
                    "deviceTime" => date('Y-m-d H:i:s', time()),
                    "equipment_no" => $data['eid'],
                    "liftingPointHeight" => (float) number_format($data['start_height'], 2, ".", ""),
                    "liftingPointRadius" => (float) number_format($data['start_range'], 2, ".", ""),
                    "startAngle" => (float) number_format($data['start_rotation_angle'], 2, ".", ""),
                    "liftingPointHeightUnload" => (float) number_format($data['end_height'], 2, ".", ""),
                    "liftingPointRadiusUnload" => (float) number_format($data['end_range'], 2, ".", ""),
                    "endAngle" => (float) number_format($data['end_rotation_angle'], 2, ".", ""),
                    "weight" => (float) number_format($data['weight'], 2, ".", ""),
                    "maxPercent" => (float) number_format($data['moment_percent'], 2, ".", ""),
                    "startRecordTime" => $data['start_time'],
                    "endRecordTime" => $data['end_time'],
                    "maxMomentEarlyAlarm" => 0,
                    "endEarlyAlarm" => 0,
                    "startEarlyAlarm" => 0,
                    "maxMomentAlarm" => 0,
                    "endAlarm" => 0,
                    "startAlarm" => 0,
                    "startPeccancy" => 0,
                    "endPeccancy" => 0,
                    "maxMomentPeccancy" => 0,
                ];
                $json = json_encode($send);
                $client = new Client;
                $response = $client->request('POST', $url, [
                    'json' => $send,
                ])->getBody();
                $stringBody = (string) $response;
                // Log::write($json, 'towerCraneWorkdata');
                // Log::write($stringBody, 'towerCraneWorkdata');
                break;
            case 3:
                //赵磊--湖北易通智联
                $host = 'https://www.etone.online/';
                $api = 'api/sendRealTimeData/';

                $token_send = [
                    'userName' => 'shandongtanyue',
                    'passWord' => 'et@20230608.',
                ];
                $client = new Client;
                $response = $client->request('POST', 'https://www.etone.online/api/login/', [
                    'form_params' => $token_send,
                ])->getBody();
                $stringBody = (string) $response;
                $token = json_decode($stringBody)->token;
                $id = json_decode($stringBody)->id;
                // $token = 'eyJ0eXAiOiJqd3QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyLCJ1c2VybmFtZSI6InNoYW5kb25ndGFueXVlIiwiZXhwIjoxNjg2NTY2OTc5fQ.Jwb45JDDVOILbfGAkSOj8dnSEbEElNOM163zl7J12Wg';
                $dtu_arr = [
                    13060825 => 'YTZL-2023-99',
                    13060830 => 'YTZL-2023-100',
                    13060811 => 'YTZL-2023-101',
                    13060829 => 'YTZL-2023-102',
                    13020350 => 'YTZL-2023-103',
                    13060824 => 'YTZL-2023-104',
                ];
                $dtu = $dtu_arr[$data['eid']];
                /* 数据 */
                $data_send[] = [
                    "sys_time" => time(),
                    "devId" => $data['eid'],
                    "typeId" => 0,
                    "startTime" => strtotime($data['start_time']),
                    "endTime" => strtotime($data['end_time']),
                    "maxMomentPer" => $data['moment_percent'],
                    "maxMoment" => 0,
                    "maxWeight" => $data['weight'],
                    "startHeight" => $data['start_height'],
                    "endHeight" => $data['end_height'],
                    "startRotation" => $data['start_rotation_angle'],
                    "endRotation" => $data['end_rotation_angle'],
                    "startRange" => $data['start_range'],
                    "endRange" => $data['end_range'],
                    "startElevation" => 0,
                    "endElevation" => 0,
                    "maxRange" => 0,
                    "maxWindSpeed" => 0,
                    "maxWind" => 0,
                    "startTravelX" => 0,
                    "startTravelY" => 0,
                    "endTravelX" => 0,
                    "endTravelY" => 0,
                    "maxLevelX" => 0,
                    "maxLevelY" => 0,
                    "momentLimit1" => 0,
                    "weightLimit1" => 0,
                    "momentLimit2" => 0,
                    "weightLimit2" => 0,
                    "upLimit1" => 0,
                    "downLimit1" => 0,
                    "turnLeftLimit" => 0,
                    "turnRightLimit" => 0,
                    "incRangeLimit" => 0,
                    "reducRangeLimit" => 0,
                    "upLimit2" => 0,
                    "downLimit2" => 0,
                ];
                $send = [
                    "name" => "123",
                    "cname" => "123",
                    "token" => $token,
                    "dtu" => $dtu,
                    "frameType" => 18,
                    "datas" => $data_send,
                    "id" => $id,
                ];
                $send_json = json_encode($send);
                $url = $host . $api;
                $client = new Client;
                $response = $client->request('POST', $url, [
                    'json' => $send,
                ])->getBody();
                $stringBody = (string) $response;
                // Log::write($stringBody, 'ForwardController106');
                break;
            case 4:
                //青岛易建智慧
                $url = 'http://221.0.183.26:9880/api/ty/tower/workData';
                $send = $data;
                $client = new Client;
                $response = $client->request('POST', $url, [
                    'json' => $send,
                ])->getBody();
                $stringBody = (string) $response;
                // Log::write($stringBody, 'towerCraneWorkdata');
                return 1;
                break;
            case 5:
                //小袁--苏州客户 筑安
                $url = 'http://material-api.huariot.com/';
                $key = 'sdtanyue001';
                $secret = '351E477205994EF48606B0E5475CE4E0';
                $getTokenUrl = 'api-gateway/api/third/v1/auth/login/';
                $token_url = $url . $getTokenUrl . '?' . 'key=' . $key . '&secret=' . $secret;
                $client = new Client;
                $response = $client->request('GET', $token_url)->getBody();
                $stringBody = json_decode((string) $response);
                $accessToken = $stringBody->data->accessToken;
                $param = $data;
                /* 设备上线 */

                $id = TowerCraneNdata::where('eid', $param['eid'])->find()->other;
                /* 实时数据添加 */
                $dataUrl = $url . 'device-socket/api/v1/third/tower-crane/work-data/';
                /*
                lifting_point_angle    Double    必选    起吊点角度
                lifting_point_range    Double    必选    起吊点幅度
                lifting_point_height    Double    必选    起吊点高度
                unload_point_angle    Double    必选    卸吊点角度
                unload_point_range    Double    必选    卸吊点幅度
                unload_point_height    Double    必选    卸吊点高度
                 */
                $send = [
                    "id" => $id,
                    "collection_time" => time() * 1000,
                    "start_time" => strtotime($data['start_time']) * 1000,
                    "end_time" => strtotime($data['end_time']) * 1000,
                    "wind" => $param['wind_speed'],
                    "safe_load_value" => 4,
                    "speed" => 1.0,
                    "obliquity" => 1.0,
                    "obliquity2" => 1.0,
                    "obliquity_direct_angle" => 1.0,
                    "load_value" => round($param['weight'] / 1000, 2),
                    "height" => $param['start_height'],
                    "angle" => $param['start_rotation_angle'],
                    "radius" => $param['start_range'],
                    "torque" => $param['moment_percent'] * 100,
                    "torque_percent" => $param['moment_percent'],
                    "lifting_point_height" => $param['start_height'],
                    "lifting_point_range" => $param['start_range'],
                    "lifting_point_angle" => $param['start_rotation_angle'],
                    "unload_point_height" => $param['end_height'],
                    "unload_point_range" => $param['end_range'],
                    "unload_point_angle" => $param['end_rotation_angle'],
                    "fall" => 2,
                    "source_from" => 'sdty',
                ];
                $send_json = json_encode($send);
                $client = new Client;
                $response = $client->request('POST', $dataUrl, [
                    'json' => $send,
                    'headers' => [
                        'Authorization' => 'Bearer ' . $accessToken,
                    ],
                ])->getBody();
                $stringBody = (string) $response;
                // Log::write($send_json, 'ForwardController112');
                // Log::write($stringBody, 'ForwardController112');
                break;
            case 6:
                $param = $data;
                //李珊珊--洛阳
                $url = 'http://api.1357.cn/hz-aiot-towercrane/api/open/tower/saveTowerWorkCircleData';
                $appId = '6182503014997891003';
                $appSecret = '841614df990649926869b2b2d3a4f8682fa41392';
                $send = [
                    "id" => time() * 1000,
                    "deviceSn" => $param['eid'],
                    "startTime" => strtotime($data['start_time']) * 1000,
                    "endTime" => strtotime($data['end_time']) * 1000,
                    "createTime" => time() * 1000,
                    "maxWeight" => $param['weight'],
                    "maxTorque" => $param['moment_percent'],
                    "maxHeight" => $param['end_height'],
                    "minHeight" => $param['start_height'],
                    "maxAmptitude" => $param['end_range'],
                    "minAmptitude" => $param['start_range'],
                    "maxRotateAngle" => $param['end_rotation_angle'],
                    "minRotateAngle" => $param['start_rotation_angle'],
                    "supplyName" => 'sdty',
                ];
                $send_json = json_encode($send);
                $client = new Client;
                $response = $client->request('POST', $url, [
                    'json' => $send,
                    'headers' => [
                        'appId' => $appId,
                        'appSecret' => $appSecret,
                    ],
                ])->getBody();
                $stringBody = (string) $response;
                // Log::write($send_json, 'ForwardController113');
                // Log::write($stringBody, 'ForwardController113');
                break;
            case 7:
                $param = $data;
                //广州兴达技术
                $url = 'https://api.xingdagz.com/v1/Tanyue/workLoopData';
                $send_json = json_encode($param);
                $client = new Client;
                $response = $client->request('POST', $url, [
                    'json' => $param,
                ])->getBody();
                $stringBody = (string) $response;
                // Log::write($send_json, 'ForwardController109');
                // Log::write($stringBody, 'ForwardController109');
                break;
            case 8:
                $param = $data;
                //福建测试
                $url = '101.133.149.245:9999/api/v1/hardware/circulation';
                $send_json = json_encode($param);
                $client = new Client;
                $response = $client->request('POST', $url, [
                    'json' => $param,
                ])->getBody();
                $stringBody = (string) $response;
                Log::write($send_json, 'ForwardController120');
                Log::write($stringBody, 'ForwardController120');
                break;
            case 9:
                //李珊珊--洛阳
                $url = 'http://api.1357.cn/hz-aiot-towercrane/api/open/tower/saveTowerWorkCircleData';
                $appId = '6182503014997891003';
                $appSecret = '841614df990649926869b2b2d3a4f8682fa41392';
                $send = [
                    "id" => time() - 365,
                    "deviceSn" => $data['eid'],
                    "startTime" => (time() - 120) * 1000,
                    "endTime" => time() * 1000,
                    "maxWeight" => $data['weight'],
                    "maxTorque" => $data['moment_percent'],
                    "maxHeight" => $data['end_height'],
                    "minHeight" => $data['start_height'],
                    "maxAmptitude" => $data['end_range'],
                    "minAmptitude" => $data['start_range'],
                    "maxRotateAngle" => $data['end_rotation_angle'],
                    "minRotateAngle" => $data['start_rotation_angle'],
                    "createTime" => time() * 1000,
                    "supplyName" => "SDTY",
                ];
                $send_json = json_encode($send);
                $client = new Client;
                $response = $client->request('POST', $url, [
                    'json' => $send,
                    'headers' => [
                        'appId' => $appId,
                        'appSecret' => $appSecret,
                    ],
                ])->getBody();
                $stringBody = (string) $response;
                Log::write($send_json, 'ForwardController113');
                Log::write($stringBody, 'ForwardController113');
                break;
            case 10:
                //江西飞达
                $url = 'https://www.zhudayun.cn/app-api/outapi/crane-cyclic';
                $send = [
                    "terminalNumber" => 'TY' . $data['eid'],
                    "time" => date('Y-m-d H:i:s', time()),
                    "startTime" => $data['start_time'],
                    "overTime" => $data['end_time'],
                    "maxLjBfb" => $data['moment_percent'],
                    "maxFs" => $data['wind_speed'],
                    "maxWeight" => $data['weight'],
                    "startHeight" => $data['start_height'],
                    "startFd" => $data['start_range'],
                    "startHzjd" => $data['start_rotation_angle'],
                    "overHeight" => $data['end_height'],
                    "overFd" => $data['end_range'],
                    "overHzjd" => $data['end_rotation_angle'],
                    "isover" => 1,
                ];
                $client = new Client;
                $response = $client->request('POST', $url, [
                    'json' => $send,
                ])->getBody();
                $stringBody = (string) $response;
                $send_json = json_encode($send);
                // Log::write($send_json, 'ForwardController125');
                // Log::write($stringBody, 'ForwardController125');
                break;
            case 11:
                //雄安滦雄科技
                if (Cache::has('CASE_127')) {
                    $token = Cache::get('CASE_127');
                } else {
                    $token_body = [
                        "appKey" => "EC2049DDFA9044178E9D10E4C2401A15",
                        "appSecret" => "AAB78C11EA82422B824B4C00044B6A0D",
                    ];
                    $token_url = 'https://api.xagongdi.com/api/open/token';
                    $client = new Client;
                    $response = $client->request('POST', $token_url, [
                        'json' => $token_body,
                    ])->getBody();
                    $stringBody = (string) $response;
                    $token = json_decode($stringBody)->data->token;
                    Cache::set('CASE_127', $token, 86400);
                }
                $send = [
                    "token" => 'a0ac9d0c1f3e9c3cf82aeb927c91008f',
                ];
                $url = 'https://api.xagongdi.com/api/open/crane/loop';
                /*
                "maximumMoment": "320",//力矩
                "maximumHeavy": "2.5",//吊重
                "maximumHeight": "25",//高度
                "maximumAmplitude": "25.2",//幅度
                "minimumMoment": "320",
                "minimumHeavy": "2.5",
                "minimumHeight": "25",
                "minimumAmplitude": "25.2",
                "liftingAngle": "256",
                "unloadingAngle": "123",
                "liftingAmplitude": "32.2",
                "unloadingAmplitude": "12.2",
                "liftingHeight": "12.6",
                "unloadingHeight": "22.6"
                 */
                $send = [
                    "token" => 'a0ac9d0c1f3e9c3cf82aeb927c91008f',
                    "serial" => $data['eid'],
                    "beginDate" => $data['start_time'],
                    "endDate" => $data['end_time'],
                    "duration" => "60",
                    "maximumMoment" => $data['moment_percent'],
                    "maximumHeavy" => $data['weight'],
                    "maximumHeight" => $data['end_height'],
                    "maximumAmplitude" => $data['end_range'],
                    "minimumMoment" => $data['moment_percent'],
                    "minimumHeavy" => $data['weight'],
                    "minimumHeight" => $data['end_height'],
                    "minimumAmplitude" => $data['end_range'],
                    "liftingAngle" => $data['start_rotation_angle'],
                    "unloadingAngle" => $data['end_rotation_angle'],
                    "liftingAmplitude" => $data['start_range'],
                    "unloadingAmplitude" => $data['end_range'],
                    "liftingHeight" => $data['start_height'],
                    "unloadingHeight" => $data['end_height'],
                ];
                $client = new Client;
                $response = $client->request('POST', $url, [
                    'json' => $send,
                ])->getBody();
                $stringBody = (string) $response;
                $send_json = json_encode($send);
                Log::write($send_json, 'ForwardController127');
                Log::write($stringBody, 'ForwardController127');
                break;
            case 12:
                //小袁-苏州中亿丰
                $param = $data;
                foreach ($param as $key => $value) {
                    $param[$key] = (float) $value;
                }
                $url = 'http://183.213.16.8:9002/devCommon/general/api/v2';
                $send['sn'] = (string) $param['eid'];
                $send['msg']['type'] = 'linux_crane_cycle';
                $send['msg']['data'] = $param;
                $send['msg']['data']['start_time'] = $data['start_time'];
                $send['msg']['data']['end_time'] = $data['end_time'];
                $client = new Client;
                $response = $client->request('POST', $url, [
                    'json' => $send,
                ])->getBody();
                $stringBody = (string) $response;
                $send_json = json_encode($send);
                Log::write($send_json, 'forwardWorkdata12');
                Log::write($stringBody, 'forwardWorkdata12');
                break;
            case 13:
                //苏州信拓业 --袁燚燚   合木探越对接尹尧
                $param = $data;
                $url = 'http://123.60.57.233:8082/ayy/api/cyclic';
                $send = [
                    "deviceId" => $param['eid'],
                    "deviceType" => 'tower',
                    "driverName" => '',
                    "startTime" => $param['start_time'],
                    "endTime" => $param['end_time'],
                    "maxWeight" => $param['weight'],
                    "startHeight" => $param['start_height'],
                    "endHeight" => $param['end_height'],
                    "startRange" => $param['start_range'],
                    "endRange" => $param['end_range'],
                    "startGyration" => $param['start_rotation_angle'],
                    "endGyration" => $param['end_rotation_angle'],
                    "sendTime" => date('Y-m-d H:i:s', time()),
                ];
                $json = json_encode($send);

                $client = new Client;
                $response = $client->request('POST', $url, [
                    'json' => $send,
                ])->getBody();
                $stringBody = (string) $response;
                Log::write($json, 'forwardWorkdata13');
                Log::write($stringBody, 'forwardWorkdata13');

                break;
            default:
                # code...
                break;
        }
    }

}
